/**
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 *         
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. Unless required by applicable law or
 * agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */
package org.rhok.ncn.background;

import android.util.Log;

/**
 * Simple background thread that runs periodically based on the specified sleep time.
 * @author pfritzsche
 */
public abstract class DaemonThread {
    private final String TAG = this.getClass().getName();
    
    private boolean isRunning = true;
    private long sleepTime;
    
    /**
     * Public constructor
     * @param sleepTime Amount of time the thread should sleep for, in millis
     */
    public DaemonThread(long sleepTime) {
        this.sleepTime = sleepTime;
    }
    
    /**
     * Thread runner.
     */
    public void start() {
        Thread thread = new Thread() {
            public void run() {
                while (isRunning) {
                    try {
                        Thread.sleep(sleepTime);
                        
                        Log.i(TAG, "Running daemon: " + TAG);
                        runOnce();
                    } catch (Exception e) {
                        Log.e(TAG, "Exception occurred in background thread: " + TAG);
                    }
                }
            }
        };
        
        thread.setDaemon(true);
        thread.start();
        
        Log.i(TAG, "Daemon started: " + TAG);
    }
    
    /**
     * Stops the thread.
     */
    public void cancel() {
        isRunning = false;
    }

    protected abstract void runOnce();
}
